package com.imglib.view;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_image_load.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.transition.platform.MaterialContainerTransform;
import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback;

import java.io.File;
import java.util.List;

import com.imglib.ImagePreviewManager;
import com.imglib.adpter.ImagePreviewAdapter;
import com.imglib.bean.ImageInfo;
import com.imglib.glide.FileTarget;
import com.imglib.glide.ImageLoader;
import com.imglib.glide.progress.OnProgressListener;
import com.imglib.glide.progress.ProgressManager;
import com.imglib.tool.HandlerUtils;
import com.imglib.tool.DownloadPictureUtil;

/**
 */
public class ImagePreviewActivity extends AppCompatActivity implements Handler.Callback, View.OnClickListener {


    // region 变量
    private Activity context;
    private HandlerUtils.HandlerHolder handlerHolder;

    private List<ImageInfo> imageInfoList;
    private int currentItem;
    private boolean isShowOriginButton;

    private ImagePreviewAdapter imagePreviewAdapter;

    private TextView tv_indicator;
    private FrameLayout fm_image_show_origin_container;
    private Button btn_show_origin;
    private ImageView img_download;
    private View rootView;
    private View progressParentLayout;


    // 指示器显示状态
    private boolean indicatorStatus = false;
    // 原图按钮显示状态
    private boolean originalStatus = false;
    // 下载按钮显示状态
    private boolean downloadButtonStatus = false;
    // 关闭按钮显示状态
    private boolean closeButtonStatus = false;
    private String currentItemOriginPathUrl = "";
    private int lastProgress = 0;

    // endregion


    // region Override 函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 只有安卓版本大于 5.0 才可使用过度动画
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
                !TextUtils.isEmpty(ImagePreviewManager.getInstance().getTransitionShareElementName())) {
            getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
            findViewById(android.R.id.content).setTransitionName("shared_element_container"); //  android.R.id.content ??
            setEnterSharedElementCallback(new MaterialContainerTransformSharedElementCallback());
            getWindow().setSharedElementEnterTransition(new MaterialContainerTransform().addTarget(android.R.id.content).setDuration(300L));
            getWindow().setSharedElementReturnTransition(new MaterialContainerTransform().addTarget(android.R.id.content).setDuration(250L));
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.sh_layout_preview);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        context = this;
        handlerHolder = new HandlerUtils.HandlerHolder(this);

        imageInfoList = ImagePreviewManager.getInstance().getImageInfoList();
        if (null == imageInfoList || imageInfoList.size() == 0) {
            onBackPressed();
            return;
        }
        currentItem = ImagePreviewManager.getInstance().getIndex();
        boolean isShowDownButton = ImagePreviewManager.getInstance().isShowDownButton();
        boolean isShowCloseButton = ImagePreviewManager.getInstance().isShowCloseButton();
        boolean isShowIndicator = ImagePreviewManager.getInstance().isShowIndicator();

        currentItemOriginPathUrl = imageInfoList.get(currentItem).getOriginUrl();

        isShowOriginButton = ImagePreviewManager.getInstance().isShowOriginButton(currentItem);
        if (isShowOriginButton) {
            // 检查缓存是否存在
            checkCache(currentItemOriginPathUrl);
        }

        rootView = findViewById(R.id.rootView);
        ViewPager viewPager = findViewById(R.id.viewPager);
        tv_indicator = findViewById(R.id.tv_indicator);

        fm_image_show_origin_container = findViewById(R.id.fm_image_show_origin_container);

        fm_image_show_origin_container.setVisibility(View.GONE);


        btn_show_origin = findViewById(R.id.btn_show_origin);
        img_download = findViewById(R.id.img_download);

        img_download.setImageResource(ImagePreviewManager.getInstance().getDownIconResId());

        // 查看与原图按钮
        btn_show_origin.setOnClickListener(this);
        // 下载图片按钮
        img_download.setOnClickListener(this);

        if (!isShowIndicator) {
            tv_indicator.setVisibility(View.GONE);
            indicatorStatus = false;
        } else {
            if (imageInfoList.size() > 1) {
                tv_indicator.setVisibility(View.VISIBLE);
                indicatorStatus = true;
            } else {
                tv_indicator.setVisibility(View.GONE);
                indicatorStatus = false;
            }
        }
        // 设置顶部指示器背景shape
        if (ImagePreviewManager.getInstance().getIndicatorShapeResId() > 0) {
            tv_indicator.setBackgroundResource(ImagePreviewManager.getInstance().getIndicatorShapeResId());
        }

        if (isShowDownButton) {
            img_download.setVisibility(View.VISIBLE);
            downloadButtonStatus = true;
        } else {
            img_download.setVisibility(View.GONE);
            downloadButtonStatus = false;
        }

        if (isShowCloseButton) {
            closeButtonStatus = true;
        } else {
            closeButtonStatus = false;
        }

        // 更新进度指示器
        tv_indicator.setText(String.format(getString(R.string.indicator), currentItem + 1 + "", "" + imageInfoList.size()));

        imagePreviewAdapter = new ImagePreviewAdapter(this, imageInfoList);
        viewPager.setAdapter(imagePreviewAdapter);
        viewPager.setCurrentItem(currentItem);
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentItem = position;
                currentItemOriginPathUrl = imageInfoList.get(position).getOriginUrl();

                isShowOriginButton = ImagePreviewManager.getInstance().isShowOriginButton(currentItem);
                if (isShowOriginButton) {
                    checkCache(currentItemOriginPathUrl);
                } else {
                    gone();
                }
                // 更新进度指示器
                tv_indicator.setText(String.format(getString(R.string.indicator), currentItem + 1 + "", "" + imageInfoList.size()));

            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            supportFinishAfterTransition();
        } else {
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

        ImagePreviewManager.getInstance().reset();
        if (imagePreviewAdapter != null) {
            imagePreviewAdapter.closePage();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.img_download) {
            downloadCurrentImg();
        } else if (i == R.id.btn_show_origin) {
            handlerHolder.sendEmptyMessage(START_SHOW_ORIGIN);
        }
    }


    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == START_SHOW_ORIGIN) {
            // 点击查看原图按钮，开始加载原图
            final String path = imageInfoList.get(currentItem).getOriginUrl();
            visible();

            btn_show_origin.setText("0 %");
            if (checkCache(path)) {
                Message message = handlerHolder.obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putString("url", path);
                message.what = DONE_LOADING;
                message.obj = bundle;
                handlerHolder.sendMessage(message);
                return true;
            }
            loadOriginImage(path);
        } else if (msg.what == DONE_LOADING) {
            // 加载完成
            Bundle bundle = (Bundle) msg.obj;
            String url = bundle.getString("url");
            gone();
            if (currentItem == getRealIndexWithPath(url)) {
                imagePreviewAdapter.loadOrigin(imageInfoList.get(currentItem));
            }
        } else if (msg.what == IS_LOADING) {
            // 加载中
            Bundle bundle = (Bundle) msg.obj;
            String url = bundle.getString("url");
            int progress = bundle.getInt("progress");
            if (currentItem == getRealIndexWithPath(url)) {
                visible();
                btn_show_origin.setText(String.format("%s %%", progress));
            }
        } else if (msg.what == HIDE_ORIGIN_BTN) {
            // 隐藏查看原图按钮
            btn_show_origin.setText(R.string.btn_original);
            fm_image_show_origin_container.setVisibility(View.GONE);
            originalStatus = false;
        } else if (msg.what == SHOW_ORIGIN_BTN) {
            // 显示查看原图按钮
            fm_image_show_origin_container.setVisibility(View.VISIBLE);
            originalStatus = true;
        }
        return true;
    }
    private final int START_SHOW_ORIGIN =0 ;
    private final int DONE_LOADING =1 ;
    private final int IS_LOADING =2 ;
    private final int HIDE_ORIGIN_BTN =3 ;
    private final int SHOW_ORIGIN_BTN =4 ;

    // endregion

    // region 对外接口
    public static void activityStart(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(context, ImagePreviewActivity.class);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            // 过度动画效果只对安卓 5.0 以上有效
            View transitionView = ImagePreviewManager.getInstance().getTransitionView();
            String transitionShareElementName = ImagePreviewManager.getInstance().getTransitionShareElementName();
            // 如果未设置则使用默认动画
            if (transitionView != null && transitionShareElementName != null) {
                ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                        (Activity) context,
                        transitionView,
                        transitionShareElementName
                );
                context.startActivity(intent, options.toBundle());
            } else {
                context.startActivity(intent);
                if (context instanceof Activity) {
                    ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
            }
        } else {
            // 低于 5.0 使用默认动画
            context.startActivity(intent);
            if (context instanceof Activity) {
                ((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        }
    }

    // endregion




    // region 内部逻辑

    /**
     * 下载当前图片到SD卡
     */
    private void downloadCurrentImg() {
        DownloadPictureUtil.downloadPicture(context.getApplicationContext(), currentItemOriginPathUrl);
    }



    public int convertPercentToBlackAlphaColor(float percent) {
        percent = Math.min(1, Math.max(0, percent));
        int intAlpha = (int) (percent * 255);
        String stringAlpha = Integer.toHexString(intAlpha).toLowerCase();
        String color = "#" + (stringAlpha.length() < 2 ? "0" : "") + stringAlpha + "000000";
        return Color.parseColor(color);
    }


    /**
     * 根据下拉关闭时的程度来 设置透明度
     */
    public void setAlpha(float alpha) {
        int colorId = convertPercentToBlackAlphaColor(alpha);
        rootView.setBackgroundColor(colorId);
        WkLog.showLog("alpha="+alpha);
        if (alpha >= 1) {
            if (indicatorStatus) {
                tv_indicator.setVisibility(View.VISIBLE);
            }
            if (originalStatus) {
                fm_image_show_origin_container.setVisibility(View.VISIBLE);
            }
            if (downloadButtonStatus) {
                img_download.setVisibility(View.VISIBLE);
            }

        } else {
            tv_indicator.setVisibility(View.GONE);
            fm_image_show_origin_container.setVisibility(View.GONE);
            img_download.setVisibility(View.GONE);
        }
    }


    private int getRealIndexWithPath(String path) {
        for (int i = 0; i < imageInfoList.size(); i++) {
            if (path.equalsIgnoreCase(imageInfoList.get(i).getOriginUrl())) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 检查缓存是否存在
     */
    private boolean checkCache(String url) {
        File cacheFile = ImageLoader.getGlideCacheFile(context, url);
        if (cacheFile != null && cacheFile.exists()) {
            gone();
            return true;
        } else {
            visible();
            return false;
        }
    }



    private void gone() {
        handlerHolder.sendEmptyMessage(HIDE_ORIGIN_BTN);
    }

    private void visible() {
        handlerHolder.sendEmptyMessage(SHOW_ORIGIN_BTN);
    }

    private void loadOriginImage(final String path) {
        Glide.with(context).downloadOnly().load(path).into(new FileTarget() {
            @Override
            public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                super.onResourceReady(resource, transition);
            }
        });

        ProgressManager.addListener(path, new OnProgressListener() {
            @Override
            public void onProgress(String url, boolean isComplete, int percentage, long bytesRead, long totalBytes) {
                if (isComplete) {// 加载完成
                    Message message = handlerHolder.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    message.what = DONE_LOADING;
                    message.obj = bundle;
                    handlerHolder.sendMessage(message);
                } else {// 加载中，为减少回调次数，此处做判断，如果和上次的百分比一致就跳过
                    if (percentage == lastProgress) {
                        return;
                    }
                    lastProgress = percentage;
                    Message message = handlerHolder.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("url", url);
                    bundle.putInt("progress", percentage);
                    message.what = IS_LOADING;
                    message.obj = bundle;
                    handlerHolder.sendMessage(message);
                }
            }
        });
    }

    // endregion





}